package com.guigu.servicegoods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.common_util.pojo.config.CacheKey;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicegoods.domain.Categorys;
import com.guigu.servicegoods.domain.TbBrand;
import com.guigu.servicegoods.domain.TbCategory;
import com.guigu.servicegoods.domain.TbCategoryBrand;
import com.guigu.servicegoods.mapper.TbCategoryMapper;
import com.guigu.servicegoods.service.TbBrandService;
import com.guigu.servicegoods.service.TbCategoryBrandService;
import com.guigu.servicegoods.service.TbCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品类目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbCategoryServiceImpl extends ServiceImpl<TbCategoryMapper, TbCategory> implements TbCategoryService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbCategoryBrandService categoryBrandService;

    @Autowired
    private TbBrandService brandService;

    @Override
    public Result findPage(Map<String, Object> searchMap, Integer page, Integer size) {
        QueryWrapper<TbCategory> wrapper = createExample(searchMap);
        //创建page对象
        Page<TbCategory> pagecategory = new Page<>(page,size);
        baseMapper.selectPage(pagecategory,wrapper);
        return Result.ok().data("row",pagecategory.getRecords()).data("total",pagecategory.getTotal());
    }

    // 封装三级分类
    @Override
    public List<Categorys> selectCategorys() {
        // 查询一级分类
        QueryWrapper<TbCategory> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id",0);
        List<TbCategory> category1List = baseMapper.selectList(wrapper1);
        // 定义封装集合
        List<Categorys> categorysList = new ArrayList<>();
        // 遍历一级分类
        for (TbCategory category1 : category1List){
            Categorys categorys = new Categorys();
            // 封装一级分类
            categorys.setId(category1.getId());
            categorys.setName(category1.getName());
            // 查询二级分类
            QueryWrapper<TbCategory> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("parent_id",category1.getId());
            List<TbCategory> category2List = baseMapper.selectList(wrapper2);
            List<Categorys> categorysList2 = new ArrayList<>();
            // 遍历二级集合
            for (TbCategory category2 : category2List){
                Categorys categorys2 = new Categorys();
                // 二级分类
                categorys2.setId(category2.getId());
                categorys2.setName(category2.getName());
                // 查询三级分类
                QueryWrapper<TbCategory> wrapper3 = new QueryWrapper<>();
                wrapper3.eq("parent_id",category2.getId());
                List<TbCategory> category3List = baseMapper.selectList(wrapper3);
                List<Categorys> categorys3List1 = new ArrayList<>();
                for (TbCategory category3 : category3List) {
                    Categorys categorys3 = new Categorys();
                    categorys3.setId(category3.getId());
                    categorys3.setName(category3.getName());
                    categorys3List1.add(categorys3);
                }
                categorys2.setChildren(categorys3List1);
                categorysList2.add(categorys2);
            }
            categorys.setChildren(categorysList2);
            categorysList.add(categorys);
        }
        return categorysList;
    }


    @Override
    public List<Map> findCategoryTree() {
        return (List<Map>)redisTemplate.boundValueOps(CacheKey.CATEGORY_TREE).get();
    }

    @Override
    public void insert(TbCategory category) {
        baseMapper.insert(category);
        saveCategoryTreeToRedis();
    }

    @Override
    public void ByIdupdate(TbCategory category) {
        baseMapper.updateById(category);
        saveCategoryTreeToRedis();
    }

    @Override
    public void ByIdremove(Integer id) {
        baseMapper.deleteById(id);
        saveCategoryTreeToRedis();
    }

    @Override
    public void saveCategoryTreeToRedis() {
        System.out.println("加载商品分类数据到缓存");
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("is_show", "1");
        wrapper.orderByDesc("seq");
        List<TbCategory> categories = baseMapper.selectList(wrapper);
        List<Map> categoryTree =findByParentId(categories,0);
        redisTemplate.boundValueOps(CacheKey.CATEGORY_TREE).set(categoryTree);
    }

    /**
     * 根据ID获取所属的品牌
     * @param id
     * @return
     */
    @Override
    public Result findByIdBrand(Integer id) {
        TbCategory category = baseMapper.selectById(id);
        QueryWrapper<TbCategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",category.getId());
        List<TbCategoryBrand> categoryBrandList = categoryBrandService.list(wrapper);
        List<TbBrand> brandList = new ArrayList<>();
        if (categoryBrandList != null) {
            for (TbCategoryBrand categoryBrand :categoryBrandList){
                TbBrand brand = brandService.getById(categoryBrand.getBrandId());
                brandList.add(brand);
            }
        }
        return Result.ok().data("brand",brandList);
    }

    private List<Map> findByParentId(List<TbCategory> categoryList, int parentId) {
        List<Map> mapList=new ArrayList<Map>();
        for(TbCategory category:categoryList){
            if(category.getParentId().equals(parentId)){
                Map map =new HashMap();
                map.put("name",category.getName());
                map.put("menus",findByParentId(categoryList,category.getId()));
                mapList.add(map);
            }
        }
        return mapList;
    }

    // 根据查询条件封装模块对象
    private QueryWrapper<TbCategory> createExample(Map<String, Object> searchMap) {
        QueryWrapper<TbCategory> wrapper = new QueryWrapper<>();
        if(searchMap!=null) {
            if(searchMap.get("id")!=null)
                wrapper.eq("id",searchMap.get("id"));
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name")))
                wrapper.like("name",searchMap.get("name"));
            if (searchMap.get("parentId")!=null)
                wrapper.eq("parent_id",searchMap.get("parentId"));
        }
        return wrapper;
    }
}
